/********************************************************************++

Copyright (c) Microsoft Corporation. All rights reserved.

************************************************************************/

using System;
using System.Data;
using System.Configuration;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Security.Cryptography;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Microsoft.Health;
using Microsoft.Health.Web;
using Microsoft.Health.ItemTypes;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        _manageLink.Visible = CheckThatSampleCanRun();
    }

    bool CheckThatSampleCanRun()
    {
        bool canRun = true;

        string sharedKeyValue = ConfigurationManager.AppSettings["HVEventingSharedKeyValue"];

        // check that the key is valid. 
        if (!String.IsNullOrEmpty(sharedKeyValue))
        {
            try
            {
                byte[] key = Convert.FromBase64String(sharedKeyValue);
                if (key.Length != 64)
                {
                    sharedKeyValue = null;
                }
            }
            catch (Exception)
            {
                sharedKeyValue = null;
            }
        }

        if (String.IsNullOrEmpty(sharedKeyValue))
        {
            c_divKeyCreation.Visible = true;

            RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();

            byte[] key = new byte[64];
            provider.GetBytes(key);

            c_keyValue.InnerText = @"<add key=""HVEventingSharedKeyValue"" value=""" +
                                    Convert.ToBase64String(key) +
                                    @"""/>";
            canRun = false;
            c_divKeyCreation.Visible = true;
        }

            // check that there is an application id. 
        string applicationIdValue = ConfigurationManager.AppSettings["ApplicationId"];

        if (String.IsNullOrEmpty(applicationIdValue))
        {

            c_ApplicationIdValue.InnerText = @"<add key=""ApplicationId"" value=""" +
                                            Guid.NewGuid().ToString() +
                                            @"""/>";
            c_divApplicationId.Visible = true;
            canRun = false;
        }

        return canRun;
    }
}
